<template lang="html">
  <div class="top-list">
    <nav-header></nav-header>
    <div class="zh-table">
      <div class="zh-table-open clear">
        <div class="zh-open-left fl">
          <div class="open-width" v-if="!isPlatform">
            <el-select v-model="platform_id" filterable placeholder="来源学校/教育局">
              <el-option
                v-for="item in schoolList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div class="open-width">
            <el-input placeholder="教师名称" v-model="keyword" @keyup.enter.native="search"></el-input>
          </div>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </div>
        <div class="zh-open-right fr">
          <el-button type="text" v-if="!isTopEducation && $store.state.checkLevel" @click="toLink('/affairs/teacherTop/push-history')">推送历史</el-button>
          <el-button type="primary" v-if="isPlatformInof== false || isPlatform == false" @click="newTeach">新增名师</el-button>
          <el-button type="danger" @click="reMoveTips()">批量移除</el-button>
        </div>
      </div>
      <div class="zh-table-contents" v-loading="dataLoading.status" :element-loading-text="dataLoading.txt">
        <el-table
          :data="listData"
          border
          @selection-change="tableSelectionChange"
          max-height="541"
          style="width: 100%">
          <el-table-column
            fixed
            type="selection"
            width="50"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="user_name"
            label="教师姓名"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="number"
            label="账号"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="subject_name"
            label="任教科目"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop=""
            label="任教班级"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{$store.state.platformInformation ? scope.row.school_name + '-' : ''}}{{scope.row.org_names}}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            prop="handle"
            label="操作"
            align="center"
            width="250"
            show-overflow-tooltip
          >

            <template slot-scope="scope">
              <!-- 多级-->
              <div v-if="scope.row.info_pt">
                <!--教育局 -->
                <div v-if="scope.row.info_ptxx">
                  <el-button  type="text"  @click.stop="toMyCenter(scope.row.user_id, scope.row.app_code)">个人主页</el-button>
                  <el-button v-if="scope.row.status==2" type="text" @click="buttonOperation(scope.row,'通过')">通过</el-button>
                  <el-button v-if="scope.row.status==2" type="text" class="delete-button" @click="buttonOperation(scope.row,'拒绝')"> 拒绝</el-button>
                  <el-button  type="text" v-show="!isTopEducation"  @click="pushTopUnit(scope.row)"> 推上级</el-button>
                  <el-button  type="text"  class="delete-button"  @click="reMoveTips(scope.row)"> 移除</el-button>
                </div>
                <!--学校 -->
                <div v-if="!scope.row.info_ptxx">
                  <el-button type="text"  @click="toMyCenter(scope.row.user_id, scope.row.app_code)">个人主页</el-button>
                  <el-button type="text" @click="pushTopUnit(scope.row)">推上级</el-button>
                  <el-button type="text"  class="delete-button" @click="reMoveTips(scope.row)">移除</el-button>
                </div>
              </div>
              <!-- 单机-->
              <div v-else>
                <el-button type="text" @click="toMyCenter(scope.row.user_id)">个人主页</el-button>
                <!-- <el-button type="text" v-if="platform" @click="pushShow(scope.row.user_id)">推上级</el-button> -->
                <el-button type="text" class="delete-button" @click="reMoveTips(scope.row)">移除</el-button>
              </div>
            </template>


          </el-table-column>
        </el-table>
        <div class="table-pagination" v-show="total_number > 10">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="listParam.page_index"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size="listParam.page_size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total_number">
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog
      title="推上级"
      :visible.sync="pushFlag"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="pushHide"
      width="40%"
    >
      <el-form ref="pushUpForm" :model="pushUpForm" label-width="80px">
        <el-form-item label="推荐理由" prop="textarea" :rules="[{validator: checkValue, required: true,message: '请输入有效值'}]">
          <div class="textarea-box">
            <el-input type="textarea" placeholder="请输入内容" v-model="pushUpForm.textarea" maxlength="200"></el-input>
            <p class="str-num"><span :class="{'str-max' : pushUpForm.textarea.length >= 200}"
                                     v-text="pushUpForm.textarea.length"></span>/<span class="str-max">200</span></p>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <p style="color: #999;">是否要将资源推送至{{ platform }}？（需经过审核）</p>
            <el-button @click="pushHide">取 消</el-button>
            <el-button type="primary" @click="upGrade">确 定</el-button>
        </span>
    </el-dialog>


    <el-dialog
      title="新增名师"
      :visible.sync="addFlag"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="cancel"
      width="500px">
      <el-form ref="addteach" :model="formDefined" label-width="80px">
        <el-form-item label="选择教师" prop="account" :rules="[{ required: true,message: '请选择教师'}]">
          <el-select
            v-model="formDefined.account"
            filterable
            @change="accountSel"
            placeholder="请输入关键词">
            <el-option
              v-for="item in accountList"
              :key="item.number"
              :label="item.name + '/' + item.number"
              :value="item.number">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="推荐理由" prop="textarea" :rules="[{validator: checkValue, required: true,message: '请输入有效值'}]">
            <div class="textarea-box">
                <el-input type="textarea" placeholder="在此填写推荐理由" v-model="formDefined.textarea" maxlength="200"> </el-input>
                <p class="str-num"><span :class="{'str-max' : formDefined.textarea.length >= 200}" v-text="formDefined.textarea.length"></span>/<span class="str-max">200</span></p>
            </div>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
            <!-- <p>将该名师推荐至佛山市教育局{{platform}}</p> -->
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="addTeach">确 定</el-button>
        </span>
    </el-dialog>

    <el-dialog
      :title="title"
      :visible.sync="examine"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="400px">
      <p style="height: 50px;">{{`是否${title =='审核通过'?'通过':'拒绝'}该名师的推送?`}}</p>
      <span slot="footer" class="dialog-footer">
            <el-button @click="examine=false">取 消</el-button>
            <el-button type="primary" @click="examineFun(title)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {debounce} from '@/tools/tool'
import {mapGetters} from "vuex";

export default {
  computed: {
    ...mapGetters({
      isPlatformInof: 'get_platformInformation',//获取当前是教育局还是学校
      isPlatform: 'checkLevel',//获取当前是单机还是多级
      userInfo:'userInfo', //用户信息
    }),
  },
  data() {
    return {
      apc: '',
      app_code: sessionStorage.getItem('CheckSchoolAppCode'),
			isTopEducation: sessionStorage.getItem('CheckSchoolAppCode') === '00000000000000000000000000000000',
      dataLoading: {
        status: false,
        txt: '获取数据...'
      },
      pushFlag: false,
      addFlag: false,
      formDefined: {
        account: '',
        textarea: '',
      },
      loading: false,
      user_id: '',
      accountList: [],
      school: '',
      schoolList: [],
      listData: [],
      listParam: {
        platform_id: null,
        keyword: '',
        page_index: 1,
        page_size: 10,
      },
      platform_id: null,
      keyword: '',
      total_number: 0,
      ids: [],
      pushId: '',
      platform: '',
      pushUpForm: {
        textarea: ''
      },
      rowLen: 0,
      title:'',
      examine:false,
      rowData:null
    }
  },
  mounted() {
  },
  created() {
    this.getEductionId();
    this.getList();
    this.platform_parent();
    if (!this.isPlatform) {//单机
      this.get_canseeposition();
    }
  },
  methods: {
    getEductionId() {
      let params = {
        app_code: this.app_code
      }
      const success = res => {
        this.listParam.platform_id = res.data.id;
      }
      this.$ajax.get('api/newlevel/platform', {
        params,
        func: { success: success }
      });
    },
    /**
     * 多级操作栏按钮方法
     * */
    buttonOperation(row,type){ //通过审核
      this.rowData = row;
      this.title = type=='通过'?'审核通过':'审核拒绝';
      this.examine = true;
    },
    //推上级
    pushTopUnit(row){
      let title = `是否要将资源推送至${this.platform}？（需经过审核）`;
        this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        }).then(() => {
          const params = {
            user_id:row.user_id
          }
          const success = (res => {
            this.getList()
            this.$message.success(res.msg)
          })
          const fail = (res => {
            this.$message.warning(res.msg)
          })

          this.$ajax.post('/api/user/teacher_master_push', params,{ func: {success, fail}})
        }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消推送'
        });          
      });
      
    },
    /**
     * 多级操作栏弹窗确认方法
     * */
    examineFun(type){
      let state = type=='审核通过'?1:3
      const params = {
        id:this.rowData.id,
        status:state,
      }
      const success = (res => {
        this.examine = false;
        this.getList();
        this.$message.success(res.msg);
      })
      const fail = (res => {
        this.examine = false;
        this.getList();
        this.$message.warning(res.msg);
      })

      this.$ajax.put('/api/user/teacher_master', params,{ func: {success, fail}})
    },
    /**
     * 新增名师
     */
    newTeach() {
      const params = {
        role_id: 6
      }
      const success = (res => {
        this.accountList = res.data;
      })
      const fail = (res => {
      })

      this.$ajax.get('api/user/user', {params, func: {success, fail}})
      this.addFlag = true;
      this.formDefined.account = undefined;

      this.$nextTick(() => {
        this.$refs.addteach.clearValidate();
      })
    },
    cancel() {
      this.$refs.addteach.clearValidate();
      this.addFlag = false;
      this.formDefined.account = '';
      this.formDefined.textarea = '';
    },
    getList() {
      let params = this.listParam;
      this.dataLoading.status = true;

      const success = res => {
        this.dataLoading.status = false;
        this.listData = res.data.data;
        console.log(res.data.data)
        this.total_number = res.data.data_sum;
        // console.log(this.isPlatform, this.isPlatformInof);
        this.listData.forEach(item => {
          this.$set(item, 'info_pt', this.isPlatform)
          this.$set(item, 'info_ptxx', this.isPlatformInof)
        })
        // console.log(this.listData);
      }
      if(this.$store.state.checkLevel) {
        this.$ajax.get('api/user/teacher_master_list', {params: params, func: {success: success}})
      }else{
        this.$ajax.get('/api/user/auth_teacher_master_list', {params: params, func: {success: success}})
      }
      
    },
    search() {
      this.listParam.keyword = this.keyword;
      this.listParam.platform_id = this.isPlatform?this.userInfo.platform_id:this.platform_id; //多级使用this.userInfo.platform_id。反之
      this.listParam.page_index = 1;
      this.getList();
    },
    reset() {
      this.platform_id = null
      this.keyword = '';
      this.listParam = {
        platform_id: null,
        keyword: '',
        page_index: 1,
        page_size: 10,
      }
      this.getList();
    },
    accountSel(val) {
      const selAccount = this.accountList.filter(ele => {
        return Object.is(ele.number, val);
      })
      this.user_id = selAccount[0].id;
    },
    addTeach() {
      let params = {
        user_id: this.user_id,
        a_comment: this.formDefined.textarea
      }
      const success = res => {
        this.$refs.addteach.clearValidate();
        this.addFlag = false;
        this.user_id = '';
        this.accountList = [];
        this.formDefined.account = '';
        this.formDefined.textarea = '';
        this.getList();
      }
      this.$refs[`addteach`].validate(valid => {
        if (valid) {
          this.$ajax.post('api/user/teacher_master', params, {func: {success: success}})
        } else {
          return;
        }
      })
    },
    toMyCenter(id, app_code) {
      
      this.apc = this.$store.state.checkLevel ? `&CheckSchoolAppCode=${app_code}` : ''

      let host_addr = sessionStorage.getItem('host_addr');
      let host = host_addr.split('://')[1];
      let token = sessionStorage.getItem('redirect_params');
      let url = `${host_addr}${token}&host=${host}&routerUrl=/teach/space&id=${id}` + this.apc;
      document.location.href = url;
    },
    checkValue(rule, value, callback) {
      if (!checkSpace(value)) {
        callback(new Error("请输入有效值"));
      } else {
        callback();
      }
    },
    get_canseeposition() {
      const success = res => {
        console.log(JSON.parse(JSON.stringify(res.data.data)))
        this.schoolList = res.data.data;
      }
      this.$ajax.get('api/level/get_canseeposition_school', {params: {}, func: {success: success}})
    },
    handleSizeChange(size) {
      this.listParam.page_size = size;
      this.getList();
    },
    handleCurrentChange(page) {
      this.listParam.page_index = page;
      this.getList();
    },
    reMoveTips(obj) {
    // console.log(this.isPlatform, 'dsfd')
      let url= '/api/user/teacher_master'
      let params = {};
      let title = null;
      console.log(obj, 88888888);
      console.log(this.ids)
      if(this.isPlatform){
        if (obj) {
          title = `确定要将 ${obj.user_name} 从名师列表中移出吗？`;
          this.ids = [obj.user_id];
        } else {
          title = '确定要将选中的教师从名师列表中移出吗？';
          
          if (this.ids.length < 1) {
            this.$message.warning('请选择需要删除的选项');
            return false;
          }
        }
        params = {
          user_id: this.ids
        }
      }else {
        if (obj) {
          title = `确定要将 ${obj.user_name} 从名师列表中移出吗？`;
          this.ids = [obj.user_id];
        } else {
          title = '确定要将选中的教师从名师列表中移出吗？';

          if (this.ids.length < 1) {
            this.$message.warning('请选择需要删除的选项');
            return false;
          }
        }
        params = {
          user_id: this.ids
        }
      }

      this.rowLen = this.ids.length;


      this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const success = res => {
          this.$message.success(res.msg);
          this.ids = [];

          if (this.listData.length - this.rowLen === 0) {
            if (this.listParam.page_index > 1) {
              this.listParam.page_index--;
            } else {
              this.listParam.page_index = 1;
            }
          }

          this.getList();
        }

        this.$ajax.delete(url, {params, func: {success: success}})
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    toLink(link) {
      this.$router.push(link);
    },
    tableSelectionChange(val) {
      this.ids = [];
      val.forEach(item => {
          this.ids.push(item.user_id)
      })
    },
    pushShow(id) {
      if (!this.platform) {
        this.$message.error('没有上级可推送了');
        return
      }

      this.pushFlag = true;
      if (this.$refs.pushUpForm) {
        this.$refs.pushUpForm.clearValidate();
      }
      this.pushId = id;
    },
    pushHide() {
      this.$refs.pushUpForm.clearValidate();
      this.pushFlag = false;
      this.pushId = '';
      this.pushUpForm.textarea = '';
    },
    platform_parent() {
      const success = res => {
        if (!is_empty(res.data)) {
          this.platform = res.data.name;
        }
      }
      this.$ajax.get('api/level/platform_parent', {params: {}, func: {success: success}})
    },
    upGrade() {
      let params = {
        user_id: this.pushId,
        a_comment: this.pushUpForm.textarea,
      }
      const success = res => {
        this.pushId = '';
        this.pushUpForm.textarea = '';
        this.$refs.pushUpForm.clearValidate();
        this.$message.success(res.msg);
        this.pushFlag = false;
        this.getList();
      }

      this.$refs[`pushUpForm`].validate(valid => {
        if (valid) {
          this.$ajax.post('api/user/teacher_master_push', params, {func: {success: success}})
        } else {
          return;
        }
      })
    }
  },
}
</script>

<style lang="scss">
.top-list {
  .el-dialog__wrapper .el-dialog__footer {
    padding: 10px 30px 30px;

    .dialog-footer > P {
      margin-top: -15px;
      color: #bbb;
      font-style: italic;
    }
  }

  .textarea-box {
    position: relative;

    .el-textarea__inner {
      min-height: 160px !important;
      resize: none;
    }

    .str-num {
      position: absolute;
      padding: 0;
      margin: 0;
      left: 0;
      bottom: 5px;
      right: 15px;
      text-align: right;

      .str-max {
        color: #ddd;
      }
    }
  }
}
</style>
